var app = angular.module("test", []);

app
		.directive(
				'epAutocomplete',
				function($parse, $http, $sce, $timeout) {
					return {
						restrict : 'EA',
						scope : {
							"id" : "@id",
							"placeholder" : "@placeholder",
							"selectedObject" : "=?",
							"dataField" : "@datafield",
							"titleAs" : "@",
							"descriptionAs" : "@",
							"imageAs" : "@",
							"inputClass" : "@inputclass",
							"userPause" : "@pause",
							"localData" : "=localdata",
							"searchFields" : "@searchfields",
							"minLengthUser" : "@minlength",
							"options" : "&",
							"valueSet" : "&"

						},
						templateUrl : 'common/templates/ep-autocomplete.html',

						link : function($scope, elem, attrs) {

							var lastSearchTerm = null;
							$scope.currentIndex = 0;
							$scope.justChanged = false;
							$scope.searchTimer = null;
							$scope.hideTimer = null;
							$scope.searching = false;
							$scope.pause = 500;
							$scope.minLength = 3;
							$scope.searchStr = null;

							if ($scope.minLengthUser && $scope.minLengthUser != "") {
								$scope.minLength = $scope.minLengthUser;
							}

							if ($scope.userPause) {
								$scope.pause = $scope.userPause;
							}

							isNewSearchNeeded = function(newTerm, oldTerm) {
								return newTerm.length >= $scope.minLength && newTerm != oldTerm
							}

							
							var getTitle = $scope.titleAs ? $parse($scope.titleAs): angular.identity;
							
							$scope.getTitle=function(result){
								return $sce.trustAsHtml(getTitle(result).toString().replace($scope.searchStr, "<strong>$&</strong>"));
							}
						
							$scope.getDescription = $scope.descriptionAs ? $parse($scope.descriptionAs)
									: angular.identity;
							$scope.getImage = $scope.imageAs ? $parse($scope.imageAs)
									: angular.identity;

							var searchTimerComplete = function(str) {
								// Begin the search

								if (str.length >= $scope.minLength) {

									$scope.options({
										query : str,
										callback : function(responseData) {
											$scope.searching = false;
											$scope.results = responseData;
										}
									});

								}

							}

							$scope.hideResults = function() {
								$scope.hideTimer = $timeout(function() {
									$scope.showDropdown = false;
								}, $scope.pause);
							};

							$scope.resetHideResults = function() {
								if ($scope.hideTimer) {
									$timeout.cancel($scope.hideTimer);
								}
								;
							};

							$scope.hoverRow = function(index) {
								$scope.currentIndex = index;
							}

							$scope.keyPressed = function(event) {
								if (!(event.which == 38 || event.which == 40 || event.which == 13)) {
									if (!$scope.searchStr || $scope.searchStr == "") {
										$scope.showDropdown = false;
										lastSearchTerm = null
									} else if (isNewSearchNeeded($scope.searchStr, lastSearchTerm)) {
										lastSearchTerm = $scope.searchStr
										$scope.showDropdown = true;
										$scope.currentIndex = 0;
										$scope.results = [];
										if ($scope.searchTimer) {
											$timeout.cancel($scope.searchTimer);
										}
										$scope.searching = true;
										$scope.searchTimer = $timeout(function() {
											searchTimerComplete($scope.searchStr);
										}, $scope.pause);
									}
								} else {
									event.preventDefault();
								}
							}

							$scope.selectResult = function(result) {

								$scope.searchStr = lastSearchTerm = getTitle(result);
								$scope.selectedObject = result;
								$scope.showDropdown = false;
								$scope.results = [];
								// $scope.$apply();
							}

							var inputField = elem.find('input');

							inputField.on('keyup', $scope.keyPressed);

							elem.on("keyup", function(event) {
								if (event.which === 40) {
									if ($scope.results
											&& ($scope.currentIndex + 1) < $scope.results.length) {
										$scope.currentIndex++;
										$scope.$apply();
										event.preventDefault;
										event.stopPropagation();
									}

									$scope.$apply();
								} else if (event.which == 38) {
									if ($scope.currentIndex >= 1) {
										$scope.currentIndex--;
										$scope.$apply();
										event.preventDefault;
										event.stopPropagation();
									}

								} else if (event.which == 13) {
									if ($scope.results && $scope.currentIndex >= 0
											&& $scope.currentIndex < $scope.results.length) {
										$scope.selectResult($scope.results[$scope.currentIndex]);
										$scope.$apply();
										event.preventDefault;
										event.stopPropagation();
									} else {
										$scope.results = [];
										$scope.$apply();
										event.preventDefault;
										event.stopPropagation();
									}

								} else if (event.which == 27) {
									$scope.results = [];
									$scope.showDropdown = false;
									$scope.$apply();
								} else if (event.which == 8) {
									$scope.selectedObject = null;
									$scope.$apply();
								}
							});

						}
					};
				});

app.controller("main", function($scope) {
	$scope.getOptions = function(query, callback) {
		var resultados = [];
		for (i = 0; i < 5; i++) {
			resultados.push({
				nombres : "Camilo Ale" + query,
				apellidos : "Navas Mo" + query,
				id : 234
			});
		}
		callback(resultados);
	}
});
